package jp.co.menox.controller.tmapp.gate;

import jp.co.menox.tmapp.dto.UserDto;
import jp.co.menox.tmapp.service.UserService;
import jp.co.menox.tmapp.util.AjaxResponse;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.gson.Gson;

public class LoginController extends Controller {

    @Override
    public Navigation run() throws Exception {
        //--------------------------------------------------------------------
        //  1. リクエストからパラメータ取得
        //--------------------------------------------------------------------
        String loginId = request.getParameter("id");
        String password = request.getParameter("password");
        
        
        //--------------------------------------------------------------------
        //  2. ステータス更新
        //--------------------------------------------------------------------
        UserService service = new UserService();
        UserDto userDto = service.userAuthentication(loginId, password);
        
        boolean ret = false;
        if (userDto != null) {
            ret = true;
        }
        
        //--------------------------------------------------------------------
        //  3. JSON変換
        //--------------------------------------------------------------------
        AjaxResponse ajaxResult = new AjaxResponse();
        ajaxResult.data = userDto;
        ajaxResult.success = ret;
        String json = new Gson().toJson(ajaxResult);
        
        
        //--------------------------------------------------------------------
        //  4. レスポンス設定
        //--------------------------------------------------------------------
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, DELETE, OPTIONS");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(json);
        
        
        return null;
    }
}